<template>
  <div>
    <div v-show="true" class="content">
      <div class="leftBarHead">
        <el-button v-show="fileListShow" type="text" class="leftBarHeadBtn" @click="fileListShow=false;">
          <el-icon size=20>
            <management/>
          </el-icon>
          文档列表
        </el-button>

        <el-button v-show="!fileListShow" type="text" class="leftBarHeadBtn" @click="fileListShow=true;">
          <el-icon size=20>
            <grid/>
          </el-icon>
          文档大纲
        </el-button>

        <el-button type="text" class="toggleBtn" @click="toggle">
          <el-icon size=20>
            <fold/>
          </el-icon>
        </el-button>

        <el-button v-show="fileListShow" type="text" class="toggleBtn" @click="createOnRoot();">
          <el-icon size=20>
            <folder-add/>
          </el-icon>
        </el-button>

      </div>

      <div class="listBar" v-show="!fileListShow">
        <div class="vditor-outline vditor" style="display: block;">
          <!--          <div class="vditor-outline__title">标题</div>-->
          <div class="vditor-outline__content listBar" id="markdown-outline"></div>
        </div>
      </div>

      <div v-show="fileListShow">
        <el-tree highlight-current
                 indent=10
                 class="listBar"
                 node-key="id"
                 check-on-click-node
                 :props="defaultProps"
                 :load="loadLeaf" lazy
                 ref="listTree"
                 @node-contextmenu="showRightMenu"
                 @node-click="handleNodeClick"
        >
          <template #default="{ node, data }">
            <div class="treeLeaf">
              <div class="itemFile" v-if="data.leaf">
                <el-icon size="15" v-show="false">
                  <notebook/>
                </el-icon>
                <span>{{ node.label }}</span>
              </div>

              <div class="itemFolder" v-else>
                <span v-if="data.isCreated" style="font-size: 16px">
                  <el-icon size="16"><folder-opened/></el-icon>
                  {{ node.label }}
                </span>
                <span v-else style="font-size: 16px">
                  <el-icon size="16"><folder-opened/></el-icon>
                  <el-input style="width:90%;font-size: 16px"
                            :ref="el => {itemRefs[data.id]=el}"
                            size="mini"/>
                </span>

              </div>

            </div>
          </template>
        </el-tree>
      </div>
    </div>

    <!--鼠标右键菜单栏，其实就是添加一个基于鼠标位置的模态框而已 -->
    <div v-show="rightMenuShow" ref="rightMenu" class="rightMenu">
      <el-card id="menu" class="menu">
        <el-button class="menuItem" type="text" v-show="!currentNodeIsLeaf" @click="operate('createdir')">
          <el-icon size="16" class="menuIcon">
            <files/>
          </el-icon>
          新建分类
        </el-button>
        <el-button class="menuItem" type="text" v-show="!currentNodeIsLeaf" @click="operate('createfile')">
          <el-icon size="16" class="menuIcon">
            <tickets/>
          </el-icon>
          新建文档
        </el-button>
        <el-button class="menuItem" type="text" @click="operate('rename')">
          <el-icon size="16" class="menuIcon">
            <edit/>
          </el-icon>
          重命名
        </el-button>
        <el-button class="menuItem" type="text" @click="operate('delfile')">
          <el-icon size="16" class="menuIcon">
            <delete-filled/>
          </el-icon>
          删除
        </el-button>
      </el-card>
    </div>
  </div>
</template>

<script>

import {
  FolderAdd, Fold, Grid, Management, FolderOpened, Notebook,
  DeleteFilled, Files, Tickets, Edit
} from '@element-plus/icons'
import {ref, onMounted, toRaw} from 'vue'
import emitter from "@/common/util/mitt.js";
import {ElMessageBox, ElMessage} from 'element-plus'
import treeMoudle from "@/common/treeMoudle";
import validator from "@/common/util/validator";

export default {
  components: {
    Grid, Fold, FolderAdd, FolderOpened, Notebook,
    Management, DeleteFilled, Files, Tickets, Edit
  },
  name: 'SideBar',
  data() {
    return {
      fileListShow: true,
      defaultProps: {
        id: 0,
        label: 'name',
        children: 'zones',
        isLeaf: 'leaf',
        isCreated: 'isCreated'
      },

    }
  },
  setup() {
    let itemRefs = {}
    const listTree = ref(null);
    let rightMenu = ref();
    let rightMenuShow = ref("false");
    let currentNodeIsLeaf = ref("false")

    let toggle = () => {
      emitter.emit('toggle', '')
    }

    let callBack = (err, refeshParent = false) => {
      if (err) {
        ElMessage({type: 'error', message: `操作失败${err}`,})
      } else {
        let node = listTree.value.getNode(listTree.value.getCurrentKey())
        if (refeshParent) {
          node = node.parent
        }
        treeMoudle().refeshNode(node)
        ElMessage({type: 'success', message: `操作成功`,})
      }
    }
    let operateDialog = (msg, tip, operate) => {
      ElMessageBox.prompt(msg, tip, {
        confirmButtonText: '确认', cancelButtonText: '取消',
        inputValidator: value => {
          return !validator().validSpecialChar(value)
        },
        inputErrorMessage: '包含违规字符！',
      })
          .then(({value}) => {
            operate(value)
          })
    }
    let createOnRoot = () => {
      ElMessageBox.prompt('请输入名称', '新建', {
        confirmButtonText: '创建', cancelButtonText: '取消',
        inputValidator: value => {
          return !validator().validSpecialChar(value)
        },
        inputErrorMessage: '包含违规字符！',
      })
          .then(({value}) => {
            window.newDir(window.HOME_DIR + window.path.sep + value, (err) => {
              if (err) {
                ElMessage({type: 'success', message: `创建${value}失败${err}`,})
              } else {
                treeMoudle().refeshNode(listTree.value.root)
                ElMessage({type: 'success', message: `创建${value}成功`,})
              }
            })
          })

    };

    let operate = (type) => {


      let node = listTree.value.getCurrentNode();
      if (type === "createdir") {
        operateDialog("新建分类", "添加", (value) => {
          window.newDir(node.path + "/" + value, callBack)
        })
      } else if (type === "createfile") {
        operateDialog("新建文档", "添加", (value) => {
          window.newFile(node.path + "/" + value + ".md", callBack)
        })
      } else if (type === "rename") {
        let parent = listTree.value.getNode(listTree.value.getCurrentKey()).parent;
        let path = ""
        if (!parent.level == 0) {
          path = parent.data.path;
        } else {
          path = window.HOME_DIR
        }
        operateDialog("重命名" + node.name, "重命名", (value) => {
          let newPath = `${path}${window.path.sep}${value}`;
          if (node.leaf) {
            newPath = newPath + ".md";
            node.name = value + ".md"
          }
          window.rename(node.path, newPath, (err) => {
            if (!err && node.leaf) {
              node.path = newPath
              handleNodeClick(node)
            }
            callBack(err, true)
          })
        })
      } else if (type === "delfile") {
        ElMessageBox.confirm("操作无法撤回，确定删除" + node.name + "吗?", '警告！',).then(() => {
          window.delFile(node.path, (err) => {
            callBack(err, true)
          })
        })
      }
    };

    let loadLeaf = (node, resolve) => {
      var result = null;
      if (node.level !== 0 && !node.data.isCreated) {
        return resolve("{}");
      }
      if (node.level === 0) {
        result = resolve(window.listDoc())
      } else {
        result = resolve(window.listDoc(node.data.path));
      }
      return result
    };

    let handleNodeClick = (node) => {
      if (node.leaf) {
        emitter.emit('update-markdown', node)
      }
    };

    let showRightMenu = (MouseEvent, object, Node, element) => {
      rightMenuShow.value = true;
      rightMenu.value.style.left = MouseEvent.clientX - 20 + "px";
      rightMenu.value.style.top = MouseEvent.clientY - 20 + "px";
      listTree.value.setCurrentKey(object.id);
      currentNodeIsLeaf.value = object.leaf;
    }


    let onFileChange = (filename, path, nodes, event) => {
      for (let i = 0; i < nodes.length; i++) {
        let item = nodes[i]
        if (item.data.path == path) {

          // changeLeaf(filename, item, path,event)
          item.loaded = false;
          item.expand();
          return true
        } else if (!item.data.leaf && item.loaded) {
          return onFileChange(filename, path, item.childNodes, event)
        }
      }
    }


    onMounted(() => {
      rightMenuShow.value = false;
      document.querySelector("#app").addEventListener('click', () => {
        rightMenuShow.value = false;
      })

      window.gwtWatcher().on('all', (event, mpath) => {
        if (event == "change") {
          return
        }
        let arrays = listTree.value.root.childNodes

        let splits = mpath.split(window.path.sep)
        let name = splits.pop()
        let fpath = splits.join(window.path.sep);
        let isFind = onFileChange(name, fpath, arrays, event)

        if (fpath == window.HOME_DIR) {
          listTree.value.root.loaded = false;
          listTree.value.root.expand();
        }

      });

    });

    return {
      itemRefs, listTree, handleNodeClick, loadLeaf, createOnRoot, showRightMenu, rightMenu,
      rightMenuShow, currentNodeIsLeaf, operate, toggle
    };
  }
}
</script>

<style>

.el-tree-node__content:hover {
  background-color: #e9ecef !important;
}

.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: #d0ebff !important;
}

.el-card__body {
  padding: unset;
}
</style>
<style scoped>
el-icon {
  margin: 2px;
}

.itemFolder {
  color: #2f3542;
  font-size: 16px;
}

.itemFile {
  font-size: 13px;

}

.menuIcon {
  float: left;
  margin-left: 5px;
  margin-right: 5px;
  display: flex;
}

.menu {
  padding: unset;
  text-align: left;
  padding: 5px;

}

.rightMenu {
  display: flex;
  position: absolute;
  z-index: 1000;
  width: 150px;
}

.menuItem {
  text-align: left;
  width: 140px;
  margin: unset;
  color: #1d2125;
}

.menuItem:hover {
  background-color: #e9ecef !important;
}

.treeLeaf {
  width: 100%;
  /*margin-top: 10px;*/
}

.treeLeaf:hover .itemIcon {
  visibility: visible;
}

.content {
  background: #f6f8fa;
  /*height: 100vh;*/
  overflow: hidden;
  /*position: relative;*/
  margin-left: 0;
  transition: margin-left 0.5s
}

.leftBarHead {
  background: #ecf0f1;
  /*position: absolute;*/
  width: 200px;
  /*height: 100%;*/
  /*text-align-all: center;*/
}

.leftBarHeadBtn {
  /*width: 70%;*/
  height: 100%;
  color: #1d2125;
  margin: unset;
}

.leftBarHeadBtn:hover {
  color: dodgerblue;

}

.toggleBtn {
  /*position: relative;*/
  /*right: -1px;*/
  color: #1d2125;
  float: right
}

.toggleBtn:hover {
  color: dodgerblue;

}

.listBar {
  background: #f6f8fa;
  height: 90vh;
  overflow: auto;
  position: absolute;
  width: 200px;
}
</style>
